# -*- coding: utf-8 -*-
"""
@Time ： 2025/3/12 9:41
@Auth ： 刘佳
@File ：DownloadThread.py
@IDE ：PyCharm
@Motto:下载依赖库
"""
import os
import platform
import subprocess
import urllib.request
import pytesseract
from PyQt5.QtCore import QThread, pyqtSignal

# Tesseract 及模型数据路径
from Util.zconfig import get_setting

TESSERACT_PATH = os.path.join(os.getcwd(), get_setting('TESSERACT')['TESSERACT_PATH'])
TESSERACT_EXE = os.path.join(TESSERACT_PATH, get_setting('TESSERACT')['TESSERACT_EXE'])  # 下载的安装文件路径


class DownloadThread(QThread):
    progress_signal = pyqtSignal(str)  # 传递进度日志
    status_signal = pyqtSignal(str)  # 状态栏信息

    def __init__(self, logger):
        super().__init__()
        self.logger = logger

    def run(self):
        os.makedirs(TESSERACT_PATH, exist_ok=True)
        headers = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36'
        }
        # 检查是否已安装视觉识别
        tFlag = False
        common_paths = [
            r"C:\Program Files\Tesseract-OCR\tesseract.exe",
            r"C:\Program Files (x86)\Tesseract-OCR\tesseract.exe"
        ]
        for path in common_paths:
            if os.path.exists(path):
                tFlag = True

        if tFlag:
            self.logger.info("视觉识别已配置过")
            return
        else:
            self.logger.info(f"开始下载视觉识别依赖库...")
            arch = '32' if platform.architecture()[0] == '32bit' else '64'
            # url = f"https://digi.bib.uni-mannheim.de/tesseract/tesseract-ocr-w{arch}-setup-v5.0.0.20211201.exe" 原地址下载速度慢,改为兰奏链接
            # 兰奏链接需要先解析成直链(项目地址https://github.com/hanximeng/LanzouAPI)
            if arch == '64':
                url = get_setting('OCR')['W64']
            else:
                url = get_setting('OCR')['W32']

            try:
                req = urllib.request.Request(url, headers=headers)
                with urllib.request.urlopen(req) as response, open(TESSERACT_EXE, 'wb') as out_file:
                    total_size = int(response.getheader('Content-Length'))
                    downloaded_size = 0
                    block_size = 8192

                    while True:
                        block = response.read(block_size)
                        if not block:
                            break
                        downloaded_size += len(block)
                        out_file.write(block)

                        percent = (downloaded_size / total_size) * 100
                        self.status_signal.emit(f"OCR支持库下载进度: {percent:.2f}%")

                self.status_signal.emit("下载完成，正在配置视觉识别...")
                subprocess.run([TESSERACT_EXE, '/S'], check=True)  # 静默安装
                # 安装完成后，删除安装文件
                os.remove(TESSERACT_EXE)
                self.status_signal.emit("配置完成")
            except Exception as e:
                self.logger.info(f"下载失败: {str(e)}")
                self.status_signal.emit("下载失败")

        # 设置 Tesseract 路径
        pytesseract.pytesseract.tesseract_cmd = TESSERACT_EXE
        self.logger.info("视觉识别已配置完成，准备使用。")
